<template>
  <div class="page-container" v-global-loading="loading">
    <div class="page-card-container">
      <!-- <div style="display: flex; justify-content: end; margin-bottom: 10px">
        <div class="commonBtn-primary" @click="modalShow">新增</div>
      </div> -->
      <a-form :model="pageSet" layout="inline">
        <a-form-item label="优惠券名称">
          <a-input
            v-model:value="pageSet.name"
            style="width: 170px"
            :allowClear="true"
          ></a-input>
        </a-form-item>
        <a-form-item label="使用区间">
          <a-range-picker
            v-model:value="pageSet.date"
            value-format="YYYY-MM-DD"
            format="YYYY-MM-DD"
          />
        </a-form-item>
        <a-form-item label="状态">
          <a-select v-model:value="pageSet.status" style="width: 130px">
            <a-select-option :value="1" title="启用">启用</a-select-option>
            <a-select-option :value="0" title="停用">停用</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="">
          <div class="commonBtn-warning" @click="loadPagination(true)">
            查询
          </div>
        </a-form-item>
        <a-form-item label="">
          <div class="commonBtn-primary" @click="modalShow">新建</div>
        </a-form-item>
        <a-form-item label="">
          <div class="commonBtn-primary" @click="reset">重置</div>
        </a-form-item>
      </a-form>
      <a-table
        size="small"
        :loading="tableLoading"
        :dataSource="tableData"
        :columns="columns"
        bordered
        :pagination="false"
        :scroll="{
          x: 1200,
          y: useAppStore.pageCommonInfo.canUseHeight - 36 + 'px'
        }"
      >
        <template #bodyCell="{text, record, index, column}">
          <template v-if="column.title == '操作'">
            <span
              class="pointer c-primaryColor"
              onselectstart="return false"
              @click="operate(1, record.id)"
              >查看</span
            >
            <span
              class="pointer c-primaryColor"
              onselectstart="return false"
              @click="operate(2, record.id, record.status)"
              >&nbsp;&nbsp;{{ record.status == 1 ? "停用" : "启用" }}</span
            >
            <span
              class="pointer c-primaryColor"
              onselectstart="return false"
              @click="operate(3, record.id)"
              >&nbsp;&nbsp;删除</span
            >
          </template>
        </template>
      </a-table>
      <Pagination
        :pageSet="pageSet"
        style="margin-top: 10px"
        :loadPagination="loadPagination"
      ></Pagination>
      <a-modal
        v-model:open="visible"
        width="800px"
        :title="title"
        :footer="null"
        :maskClosable="false"
        @cancel="cancel"
      >
        <div v-global-loading="modalloading">
          <a-form :model="form" ref="formRef" :labelCol="{span: 7}">
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item
                  label="名称"
                  name="name"
                  :rules="[{required: true, message: '请填写'}]"
                >
                  <a-input v-model:value="form.name" />
                </a-form-item>
                <a-form-item
                  label="优惠券折扣"
                  name="discount"
                  :rules="[{required: true, message: '请填写'}]"
                >
                  <a-input-number
                    style="width: 100%"
                    v-model:value="form.discount"
                    max="99"
                    min="1"
                    addon-after="%"
                  />
                </a-form-item>
                <a-form-item
                  label="发放范围"
                  name="sendScope"
                  :rules="[{required: true, message: '请填写'}]"
                >
                  <a-select v-model:value="form.sendScope" allowClear>
                    <a-select-option :value="1">全平台</a-select-option>
                    <a-select-option :value="2">指定商品</a-select-option>
                  </a-select>
                </a-form-item>
                <!-- <a-form-item
                  label="最低消费金额"
                  name="minConsumption"
                  :rules="[{required: true, message: '请填写'}]"
                >
                  <a-input v-model:value="form.minConsumption" type="number" />
                </a-form-item> -->
              </a-col>
              <a-col :span="12">
                <a-form-item
                  label="优惠券类型"
                  name="type"
                  :rules="[{required: true, message: '请选择'}]"
                >
                  <a-select v-model:value="form.type" allowClear>
                    <a-select-option :value="1">折扣</a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item label="状态" name="satus">
                  <a-select v-model:value="form.status" allowClear>
                    <a-select-option :value="0">停用</a-select-option>
                    <a-select-option :value="1">启用</a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item
                  label="可用时间"
                  name="date"
                  :format="dateFormat"
                  :rules="[{required: true, message: '请填写'}]"
                >
                  <a-range-picker
                    v-model:value="form.date"
                    value-format="YYYY-MM-DD"
                    format="YYYY-MM-DD"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-form-item label="描述" name="description" :labelCol="{span: 3}">
              <a-textarea v-model:value="form.description" />
            </a-form-item>
          </a-form>
          <discountProduct
            ref="discountProductRef"
            v-model:list="productData"
            v-if="form.sendScope == 2"
          >
          </discountProduct>
          <div style="display: flex; justify-content: end">
            <a-button style="margin-right: 14px" @click="cancel">取消</a-button>
            <a-button type="primary" @click="isOk">确定</a-button>
          </div>
        </div>
      </a-modal>
    </div>
  </div>
</template>

<script lang="ts" setup>
import {ref, inject, onActivated, onMounted, computed} from "vue";
import Pagination from "@/components/pagination/Pagination.vue";
import useAppStore from "@/store/app";
import {
  createDiscount,
  queryDiscount,
  changeStatus,
  discountDetail,
  updateDiscount,
  deleteDiscount
} from "@/api/discount/discountList";
import dayjs, {Dayjs} from "dayjs";
const calcCanUseHeight: any = inject("calcCanUseHeight");
import {message, Modal} from "ant-design-vue";
import discountProduct from "@/components/functional/discountProduct.vue";
const reset = () => {
  pageSet.value = {
    pageNo: 1,
    pageSize: 20,
    total: 0
  };
  loadPagination();
};
onActivated(() => {
  calcCanUseHeight();
});
onMounted(() => {
  calcCanUseHeight();
});
const tableLoading = ref<boolean>(false);
const loading = ref<boolean>(false);
const visible = ref(false);
const form = ref<any>({});
const formRef = ref();
const modalloading = ref<boolean>(false);
const productData: any = ref([]);
const title = ref("新增");
const dateFormat = "YYYY-MM-DD";
const pageSet = ref<any>({
  pageNo: 1,
  pageSize: 20,
  total: 0
});

//获取数据
const loadPagination = (flag: boolean = false): void => {
  if (flag) {
    pageSet.value.pageNo = 1;
  }
  if (pageSet.value.date) {
    pageSet.value.startDate = pageSet.value.date[0];
    pageSet.value.endDate = pageSet.value.date[1];
  } else {
    pageSet.value.startDate = null;
    pageSet.value.endDate = null;
  }
  tableLoading.value = true;
  queryDiscount(pageSet.value)
    .then((res) => {
      tableData.value = res.data.rows;
      pageSet.value.total = res.data.totalRows;
    })
    .finally(() => {
      tableLoading.value = false;
    });
};
loadPagination(true);
//导出
const tableData = ref<Array<object>>([]);
const columns = ref<Array<object>>([
  {
    title: "序号",
    dataIndex: "name",
    align: "center",
    width: 50,
    customRender: ({index}) => {
      return index + 1;
    },
    fixed: "left"
  },
  {
    title: "优惠券名称",
    dataIndex: "name",
    align: "center",
    width: 200
  },
  {
    title: "优惠券折扣",
    dataIndex: "discount",
    align: "center",
    width: 120
  },
  // {
  //   title: "最低消费",
  //   dataIndex: "minConsumption",
  //   align: "center",
  //   width: 100
  // },
  {
    title: "类型",
    dataIndex: "type",
    align: "center",
    width: 120,
    customRender: ({value}) => {
      if (value == 1) {
        return "折扣";
      } else {
        return "其他";
      }
    }
  },
  {
    title: "优惠券开始使用时间",
    dataIndex: "startDate",
    align: "center",
    width: 150,
    customRender: ({value, record}) => {
      if (record.endDate !== null && record.startDateDate !== null) {
        return dayjs(value).format("YYYY-MM-DD");
      } else {
        return "";
      }
    }
  },
  {
    title: "优惠券使用结束时间",
    dataIndex: "endDate",
    align: "center",
    width: 150,
    customRender: ({value, record}) => {
      if (record.endDate !== null && record.startDateDate !== null) {
        return dayjs(value).format("YYYY-MM-DD");
      } else {
        return "";
      }
    }
  },
  {
    title: "优惠券有效期",
    dataIndex: "date",
    align: "center",
    width: 120,
    customRender: ({value, record}) => {
      if (record.endDate !== null && record.startDateDate !== null) {
        const endDate = dayjs(record.endDate, dateFormat);
        const startDate = dayjs(record.startDate, dateFormat);
        value = endDate.diff(startDate, "day");
        return value + "天";
      }
    }
  },
  {
    title: "发放范围",
    dataIndex: "sendScope",
    align: "center",
    width: 200,
    customRender: ({value}) => {
      if (value == 1) {
        return "全平台";
      }
      if (value == 2) {
        return "指定商品";
      } else {
        return "其他";
      }
    }
  },
  {
    title: "状态",
    dataIndex: "status",
    align: "center",
    width: 120,
    customRender: ({value}) => {
      if (value == 0) {
        return "停用";
      } else if (value == 1) {
        return "启用";
      }
    }
  },
  {
    title: "操作",
    dataIndex: "l",
    align: "center",
    width: 120,
    fixed: "right"
  }
]);
//新增优惠券
const modalShow = () => {
  form.value = {};
  visible.value = true;
  title.value = "新增";
};
// 点击弹框确定
const isOk = () => {
  formRef.value.validate().then(() => {
    if (productData.length !== 0) {
      form.value.productIds = productData.value.join(",");
    }
    form.value.startDate = form.value.date[0];
    form.value.endDate = form.value.date[1];
    const formData = JSON.parse(JSON.stringify(form.value));
    if (formData.sendScope == 2 && !formData.productIds.length) {
      return message.error("请选择指定商品");
    }
    modalloading.value = true;
    if (formData.id) {
      updateDiscount(formData)
        .then(() => {
          message.success("修改成功");
          loadPagination(true);
          visible.value = false;
          form.value = {};
        })
        .finally(() => {
          modalloading.value = false;
        });
    } else {
      createDiscount(formData)
        .then(() => {
          message.success("新增成功");
          loadPagination(true);
          visible.value = false;
          form.value = {};
        })
        .finally(() => {
          modalloading.value = false;
        });
    }
  });
};
const cancel = () => {
  formRef.value.clearValidate();
  visible.value = false;
  form.value = {};
  productData.value = [];
};
// 操作
const operate = (type: Number, id: number | string, status?: number) => {
  if (type == 1) {
    //查看
    title.value = "详情";
    getDetail(id);
  } else if (type == 2) {
    // 状态修改
    // loading.value = true;
    let statusFlag = status == 0 ? 1 : 0;
    let name = status == 0 ? "启用" : "停用";
    Modal.confirm({
      title: `确定要${name}该优惠券吗？`,
      onOk() {
        changeStatus({id, status: statusFlag})
          .then((res) => {
            message.success("修改成功！");
            loadPagination(true);
          })
          .finally(() => {
            loading.value = false;
          });
      }
    });
  } else if (type == 3) {
    //删除
    Modal.confirm({
      title: "确定要删除该数据嘛",
      onOk() {
        loading.value = true;
        deleteDiscount({id})
          .then(() => {
            message.success("删除成功！");
            loadPagination(true);
          })
          .finally(() => {
            loading.value = false;
          });
      }
    });
  }
};
const getDetail = (id: string | number) => {
  loading.value = true;
  discountDetail({id})
    .then((res) => {
      form.value = res.data;
      form.value.endDate = dayjs(res.data.endDate, dateFormat);
      form.value.startDate = dayjs(res.data.startDate, dateFormat);
      form.value.date = [form.value.startDate, form.value.endDate];
      if (form.value.productIds !== null) {
        productData.value = form.value.productIds.split(",");
      }
    })
    .finally(() => {
      loading.value = false;
      visible.value = true;
    });
};
</script>

<style lang="less" scoped></style>
